﻿using System;
using System.Collections.Generic;
using System.IO;
using System.ServiceModel;
using System.Web;
using SecurityClient;

namespace SecurityModule.Workflows
{
    class WFGetSetupVerify : SimpleWorkflow
    {
        public WFGetSetupVerify()
        {
            Verb = "GET";
            Path = "/Setup/Verify";
        }

        public override void PreProcessImplementation(HttpContext context)
        {
            try
            {
                // Lookup VerificationToken contained in querystring and inject the fields into the form
                // Anon is attempting to confirm their identity
                var tokenId = context.Request.QueryString["VerificationToken"];
                if (string.IsNullOrEmpty(tokenId)) return;
                var security = new SecurityServiceProxy();
                var email = security.GetTokenFieldValue(tokenId, "EmailAddress") as string;
                var clientCode = security.GetTokenFieldValue(tokenId, "ClientCode") as string;
                if (!string.IsNullOrEmpty(email) && !string.IsNullOrEmpty(clientCode))
                {
                    //inject ClientCode and EmailAddress
                    AddToForm(context.Request, new Dictionary<string, string>
                    {
                        {"Email", email},
                        {"ClientCode", clientCode},
                    });
                }
            }
            catch (Exception exception)
                {
                    if (exception is PipeException || exception is EndpointNotFoundException)
                    {
                        AddToForm(context.Request, new Dictionary<string, string>
                            {
                                {"EXTERRMSG", SecurityServiceDownMsg}
                            });
                    }
                    else
                    {
                        AddToForm(context.Request, new Dictionary<string, string>
                            {
                                {"EXTERRMSG", exception.Message}
                            });
                    }
                }
            // show Yubikey Field
            context.Response.Filter = new ReplaceFilter(
                context.Response.Filter,
                context.Response.ContentEncoding,
                new Dictionary<string, string>
                    {
                        {
                            "{{YubikeyOTP}}",
                            @"<label class='control-label' for='YubikeyOTP'>Yubikey</label><input name='YubikeyOTP' type='text' class='form-control'>"
                        }
                    }
                );
        }



        public override void PostProcessImplementation(HttpContext context)
        {

        }
    }
}
